import {Action, configureStore, ThunkAction} from '@reduxjs/toolkit';
import {PersistConfig, persistReducer, persistStore} from 'redux-persist';
import storage from 'redux-persist/lib/storage'; // 默认使用localStorage
// import storageSession from 'redux-persist/lib/storage/session';
import rootReducer from './reducers.ts'; // 假设已合并所有reducers

// 定义 RootState 类型
export type RootState = ReturnType<typeof rootReducer>;
export type AppThunk<ReturnType = void> = ThunkAction<ReturnType, RootState, unknown, Action>;

// Persist配置
const persistConfig: PersistConfig<RootState> = {
    key: 'root', // 存储的键名
    storage: storage,      // 存储引擎, 可选 storageSession
    whitelist: ['auth', 'app'], // 只持久化auth reducer
    // blacklist: ['temp'], // 排除不需要持久化的reducer
};

// 增强后的reducer
const persistedReducer = persistReducer(persistConfig, rootReducer);

// 创建store
export const store = configureStore({
    reducer: persistedReducer,
    middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware({
            serializableCheck: false, // 关闭序列化检查（避免persist触发警告）
        }),
});

// 创建持久化器
export const persist = persistStore(store);
export type AppDispatch = typeof store.dispatch;